from datetime import datetime
import requests
import json
import time

#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
#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
#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
openai_key = "sk-FGV2ay0guo9IGCh1yEY19Jd3felfr63RcWk0TIRx1emXBybm"

openai_url = "https://api.chatanywhere.tech/v1/chat/completions"


# subject = "食品加工"
# title = "不同加工工艺对药材菊花香气成分的影响研究"
current_date = datetime.now()

# 设置请求头，包括授权信息
def generate_content(subject_str, title_str):
    subject = subject_str
    title   = title_str
    print(subject, title)
    def openai_request(content, modle="gpt-3.5-turbo-0125", max_tokens=1200, temperature=0.8):
        headers = {
            "Authorization": f"Bearer {openai_key}",
            "Content-Type": "application/json"
        }
        # 设置请求体，包含提示，引擎，最大令牌数，温度，停止符等参数
        data = {
            "messages":  [
            {
                "role": "system",
                "content": f"You are ChatGPT, a large language model trained by OpenAI.Knowledge cutoff: 2021-09Current date: {current_date}"
            },
            {
                "role": "user",
                "content": content
            }
        ],
            "model": modle,
            "max_tokens": max_tokens,
            "temperature": temperature,
            "stream":False
        }
        data = json.dumps(data)
        response = requests.post(openai_url, headers=headers, data=data)
        print("请求成功开始撰写")
        story = response.json()["choices"][0]["message"]["content"]
        return story



    ##摘要处理
    abstract_prompt = f"我开始写论文了，题目是：{title}，请你提供更具体的细节，以支持论点或想法，完成500字摘要。并为这篇论文写出几个关键词"
    print("开始撰写: 摘要 ")
    abstract_ai = openai_request(abstract_prompt)
    abstract = f"{abstract_ai}"
    print("已完成")
    # time.sleep (22)
    



    #大纲处理，分离出大纲
    def ex_outline():
        outline_prompt = f"我想写一篇{subject}专业关于{title}的论文，请帮我拟定一份论文大纲。格式:按照二级标题列出提纲。一级标题是中文数字，二级标题是（一），给出一级和二级标题即可。 格式案例:以下仅仅是一个格式的例子，你写的时候按照这个格式写，但是内容按照你自己的思路写。 一、引言 （一）研究的背景以及意义 （二）…"
        outline_ai = openai_request(outline_prompt)
        # time.sleep (10)
        outline_text = f"{outline_ai}"


###########多余代码#####################
        # print(outline_text)
        # outline = [] 
        # lines = outline_text.split("\n")
        # for line in lines:
        #     if line.startswith(("一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "1", "2", "3", "4", "5", "6", "（" ,"）", "(", ")")):
        #         outline.append(line)
        #     else:
        #         continue
        # outline = "\n".join(outline)
###########多余代码#####################
        
        return outline_text
    outline_te = f'{ex_outline()}'
    print(outline_te)

    #正文处理
    def body():
        outline_ex = ex_outline() #论文大纲
        outline_list = outline_ex.split("\n") # 将大纲分割成列表
        # 初始化一个空字符串，用于存储正文内容
        content_list = ""
        for item in outline_list:
            if item.startswith(("一", "二", "三", "四", "五", "六", "七", "八", "九", "十")):
                print(f"开始撰写:{item}")
                print(f"已完成")
                content_list += f"{item}\n"
            elif item.startswith(("（", "）", "(", ")")):
                print(f"开始撰写:{item}")
                content_prompt =f"我正在撰写一篇长论文，文章标题为：{title}文章目录为：{outline_ex}请撰写{item}的内容,以下是写作要求 ：1.请结合{item}内容确保结构清晰，信息丰富，2.请使用你自己组织的语言并保证低查重率3.只输出正文即可不要输出标题。4.不要输出我所提供的{item}"
                content_ai = openai_request(content_prompt)
                content = f"{content_ai}"
                content_list += f"{item}\n{content}\n"
                print(f"已完成")
                # time.sleep (60)
                # print(f'当前段落内容为:{content_list}')
        return content_list


    #正文部分
    body_text = f"{body()}"
    
    print (body_text)

    # 生成论文内容
    paper = []
    paper.append(title + '\n' + abstract + '\n' + body_text + '\n')
    print(paper)


    #写入txt文档以文件名加时间戳命名
    file_name = f"{title}.txt"
    # 打开文件并以UTF-8编码写入文本内容
    with open(file_name, 'w', encoding='utf-8') as file:
        file.write('\n'.join(paper))

    print(f"文件 '{file_name}' 已创建并写入内容。")
    return paper